import time, os
from machine import SPI, Pin
import lib.st7735_buf as st7735_buf
from lib.easydisplay import EasyDisplay
from lib.sdcard import SDCard

# 初始化TFT的 CS 和 DC 引脚
tft_cs = Pin(5, Pin.OUT)
tft_dc = Pin(4, Pin.OUT)

# 初始化 SD 卡的 CS 引脚
sd_cs = Pin(22, Pin.OUT)

# 定义一个函数来切换 SPI 设备
def switch_spi_device(device):
    global spi2
    if device == 'tft':
        # 初始化SPI对象以适用于 LCD
        spi2=SPI(2, baudrate=40000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23))
    elif device == 'sdcard':
        # 初始化SPI对象以适用于 SD 卡
        spi2=SPI(2, baudrate=40000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))

# 初始化LCD屏幕
def init_lcd():
    switch_spi_device('tft')
    dp = st7735_buf.ST7735(width=160, height=128, spi=spi2, cs=tft_cs, dc=tft_dc, res=19, rotate=1, bl=None, invert=False, rgb=False)
    ed = EasyDisplay(dp, "RGB565", font="/font/text_lite_16px_2312.v3.bmf", show=True, color=0xFFFF, clear=True, auto_wrap=True)
    return ed, dp

# 初始化SD卡
def init_sd():
    global sd
    switch_spi_device('sdcard')
    sd = SDCard(spi2, sd_cs)

if __name__ == "__main__":
    # 读取SD卡的TXT
    init_sd()
    os.mount(sd, '/sd')
    print("SD card mounted")
    f = open("/sd/a.txt", "r") 
    read_txt = f.read()  # 读取文件的全部内容
    f.close()

    # 初始化并获取 EasyDisplay 和 Display 对象
    ed, dp = init_lcd()

    # 在LCD上显示文本信息
    ed.text(read_txt, 0, 0)

    time.sleep(3)

    # 再次读取SD卡的TXT
    init_sd()
    f = open("/data/book.txt", "r") 
    read_txt2 = f.read()  # 读取文件的全部内容
    f.close()

    # 再次显示文本信息
    ed.text(read_txt2, 0, 0)
